import os.path

import pandas as pd
import numpy as np
from netmiko import ConnectHandler,SSHDetect, Netmiko
import threading


def show_ip_interface_brief(output):
    #解析show ip interface brief
    output1=output.split('\n')
    output2=[re.split(r'\s+',x.strip()) for x in output1]
    output_ip_interface=pd.DataFrame(output2[1:],columns=output2[0]) #output2必须要是单列表
    return output_ip_interface


def netmiko_collect_info(host_ip,command,path):
    dev = {
        'device_type': 'zte_zxros',
        'host':   host_ip,
        'username': 'zte',
        'password': 'zte',
        'port' : 22,          # optional, defaults to 22
    }

    net_connect = ConnectHandler(**dev)
    output = net_connect.send_command(command)
    print(output)
    #调用指令函数，处理响应的输出结果，处理为pd.DataFrame格式
    command_fun=eval(command.replace(' ','_'))()
    result=command_fun(output)
    result['host_ip']=host_ip #增加字段host_ip,标识设备

    base_dir=path+command+'\\'
    if not os.path.exists(base_dir):
        # 如果不存在，创建目录
        os.mkdir(base_dir)
        print(f"Directory '{base_dir}' created successfully")
    else:
        print(f"Directory '{base_dir}' already exists")

    result.to_csv(base_dir+host_ip+'.csv')#将同一指令的文件存储到相同的文件夹中
    return result


def batch_send_command(host_ip_list,command,path):
    #批量给多台设备下发指令
    for i in range(0,len(host_ip_list)):
        t = threading.Thread(target=netmiko_collect_info, args=(host_ip_list[i], command, path))
        t.start()


def concat_file(path,command):
    #合多台设备同一个command的输出结果
    base_dir=path+command+'\\' #获取command输出的目录


    file_name=os.listdir(base_dir) #获取base_dir目录下的所有文件
    command_result_all=pd.DataFrame()
    for x in file_name:
        path_final=os.path.join(base_dir,x)
        file=pd.read_csv(path_final)
        command_result_all=pd.concat(command_result_all,file)#合并多个主机的command的输出结果

    return command_result_all



path='E:\\江苏移动-hzy工作资料\\5GC学习资料\\01-中兴5GC资料\\python-tasks\\'

host_ip_list=['129.60.161.169', '129.60.161.170']
commands=['show ip interface brief']


commands_result_all={}
for command in commands:
    batch_send_command(host_ip_list,command,path)
    commands_result_all[command]=concat_file(path,command)



output_ip_interface[output_ip_interface['Interface'] == 'xgei-0/2/0/3']
down_interface=output_ip_interface[output_ip_interface['Admin']=='down']['Interface']





config_commands=[]
for x in dowm_interface:
    config_commands.append('interface '+x )
    config_commands.append('no shutdown')
    config_commands.append('exit')

output = net_connect.send_config_set(config_commands)
print(output)



